const path = require("path")
const fs = require("fs")
const url = require("url")
const connect = require("../model")

const uploadcontroller = {

    //  接受文件
    async addfile(req, res) {

        let { orderid, type } = req.body
        let rootpath = path.resolve(__dirname, "../", req.file.destination)
        let filepath = rootpath + "\\" + req.file.filename

        var str = req.file.originalname
        let houzhui = str.substring(str.lastIndexOf("."))
        var newname = filepath + houzhui
        var httpname = url.format("/" + req.file.path + houzhui).replace("/static", "")
        fs.renameSync(filepath, newname)

        let sql = `INSERT into orderstatic(orderid , type,link,name) VALUES( ? , ? , ? ,?)  `
        let [data] = await connect.query(sql, [orderid, type, "http://127.0.0.1:3200" + httpname, req.file.originalname])

        res.json({
            code: 2000,
            mesage: "成功",
            data: {
                id: data.insertId,
                url: "http://127.0.0.1:3200" + httpname
            }
        })
    },
    async addfile2(req, res) {

        let { orderid, type } = req.body
        let rootpath = path.resolve(__dirname, "../", req.file.destination)
        let filepath = rootpath + "\\" + req.file.filename

        var str = req.file.originalname
        let houzhui = str.substring(str.lastIndexOf("."))
        var newname = filepath + houzhui
        var httpname = url.format("/" + req.file.path + houzhui).replace("/static", "")
        fs.renameSync(filepath, newname)

        // let sql = `INSERT into orderstatic(orderid , type,link,name) VALUES( ? , ? , ? ,?)  `
        // let [data] = await connect.query(sql, [orderid, type, "http://127.0.0.1:3200" + httpname, req.file.originalname])

        res.json({
            code: 2000,
            mesage: "成功",
            data: {
                url: "http://127.0.0.1:3200" + httpname
            }
        })
    },

    async deletefile(req, res) {
        let { id } = req.body
        //  先查询数据库的文件名称 
        //  再删除 
        let sql = "select * from orderstatic where id = ?"
        let [data] = await connect.query(sql, [id])
        url.parse(data[0].link).pathname
        let str = path.resolve(__dirname, "../static/" + url.parse(data[0].link).pathname)
        fs.unlinkSync(str)
        let sql2 = "DELETE FROM orderstatic WHERE id  = ?;"
        await connect.query(sql2, [id])
        res.json({
            code: 2000,
            message: "删除成功"
        })

    }


}


module.exports = uploadcontroller